package com.wnxy.service;

import com.wnxy.pojo.Goods;
import com.wnxy.repository.GoodsRepository;
import com.wnxy.utils.JsoupUtils;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class GoodsService {
    @Autowired
    private GoodsRepository goodsRepository;
    @Autowired
    private ElasticsearchRestTemplate restTemplate;

    /**
     * 根据关键字，爬取京东数据
     * @param keyword
     */
    public void parseJd(String keyword) throws Exception {
        List<Goods> list = JsoupUtils.parseJd(keyword);
        goodsRepository.saveAll(list);
    }

    /**
     * 搜索索引库
     */
    public List<Goods> search(String keyword, Integer pageNum, Integer pageSize) {
        // 条件构造器
        NativeSearchQueryBuilder builder =
                new NativeSearchQueryBuilder()
                    .withQuery(QueryBuilders.matchQuery("name",keyword))
                    .withPageable(PageRequest.of((pageNum-1),pageSize));
        // 高亮处理； 比如搜索的关键字是：java， 高亮实现：<span style='color:red'>java</span>
        builder.withHighlightFields(new HighlightBuilder.Field("name")
                .preTags("<span style='color:red'>")
                .postTags("</span>")
        );

        // 搜索
        SearchHits<Goods> searchHits =
                restTemplate.search(builder.build(), Goods.class);
        // 处理结果, 返回List<Goods>对象
        List<Goods> list =
                searchHits.stream().map(serchHit123->{
                    Goods goods = serchHit123.getContent();
                    // 获取高亮内容
                    List<String> highList = serchHit123.getHighlightField("name");
                    if (!CollectionUtils.isEmpty(highList)) {
                        goods.setName(highList.get(0));
                    }
                    return goods;
                }).collect(Collectors.toList());
        return list;
    }
}
